package model;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * Created by admin
 * <p>
 * Date :2020/10/13
 * <p>
 * Description :
 * <p>
 * Version :1.0
 */
public class Game {
    private static final Logger logger = LoggerFactory.getLogger(Game.class);

    /**
     * 扑克牌
     */
    private Pocker pocker;

    /**
     * 玩家
     */
    private List<PockerPlayer> playerList = new LinkedList<>();

    /**
     * 当前玩家
     */
    private PockerPlayer<Player> currentPlay = null;

    /**
     * 庄家
     */
    private PockerPlayer master = null;

    /**
     * 裁判
     */
    private Referee referee;

    public Game() {
        this.pocker = new Pocker();
    }

    public Game(Pocker pocker) {
        this.pocker = pocker;
    }


    /**
     * 玩家加入
     * @param player
     * @return
     */
    public Game join(Player player) {
        if(!playerList.contains(player)){
            PockerPlayer pockerPlayer = new PockerPlayer(player);
            playerList.add(pockerPlayer);
            if(currentPlay == null){
                currentPlay = master = pockerPlayer;
            }else{
                currentPlay.next = pockerPlayer;
                currentPlay = pockerPlayer;
            }
        }else{
            logger.warn("尊敬的{}已经在游戏房间，不能重复进入", player.getName());
        }
        return this;
    }

    /**
     * 准备好扑克牌
     * @param pocker
     * @return
     */
    public Game pocker(Pocker pocker) {
        pocker = pocker;
        return this;
    }

    /**
     * 是否准备就绪
     * @return
     */
    public boolean idReady() {
        return playerList.size() > 0 && pocker != null && referee != null;
    }

    /**
     * 开始游戏
     */
    public void start() throws Exception {
        if(!idReady()){
            logger.warn("准备未就绪不能开始游戏");
        }

        currentPlay.next = master;


        //庄家
        Random random = new Random();

        //需要发牌的个数
        int card_count = playerList.size() * GoldenFlower.POCKER_COUNT;

        //裁判洗牌，发牌
        referee.shufflePocker(pocker).castPocker(pocker, card_count, pockerCard -> {
            GoldenFlower goldenFlower = currentPlay.getGoldenFlower();
            if(goldenFlower == null){
                goldenFlower = new GoldenFlower();
                currentPlay.setGoldenFlower(goldenFlower);
            }
            goldenFlower.catching(pockerCard);
            currentPlay = currentPlay.next;
        });

        //比大小
        boolean isWin = referee.judge(master, master.next);
        logger.info("您{}", isWin ? "赢了！恭喜！！！" : "输了...");
        logger.info("您的牌{}", master.getGoldenFlower());
        logger.info("对方的牌{}", master.next.getGoldenFlower());

    }


    public Game referee(Referee referee) {
        this.referee = referee;
        return this;
    }
}
